#include "hoopoe.h"

// This function returns FAILURE if file name is not a installer package
// This function returns SUCCESS if file name is a installer package
unsigned int 
IsFileInstaller
(
 LPFileInfo pFileToBeAnalyzed
)
{
	unsigned int retVal = FAILURE;
	unsigned char *FilePtr;
	int count_sign=0;

	//define EXE Signature
	//4D 5A

	FilePtr=(unsigned char *)pFileToBeAnalyzed->lpFileBase;
	
	while (count_sign < 2 )
	{
		if(FilePtr[count_sign] != exe_signature[count_sign])
		{
			count_sign=-1;
			break;

		}
		count_sign++;
	}

		if(count_sign == -1)
			return FAILURE;
		else
			return SUCCESS;

	return FAILURE;
}




	return FAILURE;
}

// This function returns FAILURE if file name is not a installer package
// This function returns SUCCESS if file name is a installer package
unsigned int 
IsFileMSIPackage
(
 LPFileInfo pFileToBeAnalyzed
)
{
	unsigned int retVal = FAILURE;
	unsigned char *FilePtr;
	int iCount = 0;

	// define MSI Signature
	// D0 CF 11 E0 A1 B1 1A E1 00

	FilePtr = (unsigned char *)pFileToBeAnalyzed->lpFileBase;
	
	while(iCount < 9)  {

		if(FilePtr[iCount] != msi_signature[iCount]){
			iCount=-1;		
			break;
		}

		++iCount;
	}

	if(iCount == -1)
		return FAILURE;
	else if(iCount == 9)
		return SUCCESS;

	return FAILURE;
}


// This function returns FAILURE if file name is not a installer package
// This function returns SUCCESS if file name is a installer package
unsigned int 
IsInstallerPackage
(
 wstring argFileName
)
{
	unsigned int retVal = FAILURE;
	DWORD		 dwType = 0;
	unsigned char fAnalyze = 0;

	FileInfo FI;
	FI.FileName = argFileName;

	if( GetBinaryTypeW(FI.FileName.c_str() , &dwType) )
	{
		if( (dwType == SCS_64BIT_BINARY)	|| (dwType == SCS_32BIT_BINARY) ) 	
			fAnalyze = 1;
	}
	
	if(SUCCESS != GetFileForAnalysis(&FI) ){
	
		wcout<< argFileName <<L" could not be opened for analysis because of Error: "<<GetLastError()<<endl;
		return FAILURE;

	}

	// We first check if file is a binary, then we analyze it
	// other wise we check it again for msi package, if it is msi package then we call it an installer
	// otherwise it is not an installer.
	//
	if(fAnalyze)	
		 return IsFileInstaller(&FI);
	else
		 return IsFileMSIPackage(&FI) ;
}


// main
int wmain(int argc, wchar_t *argv[])
{
	unsigned int retVal = FAILURE;

	// check the command line arguments
	if(argc != 2) {
		cout<<"Enter File Path as an argument"<<endl;
		return 0;
	}

	wstring FileName;
	FileName = argv[1];

	retVal = IsInstallerPackage(FileName);
	if(retVal == SUCCESS)
		cout<<"This IS an installer package"<<endl;
	else
		cout<<"This IS NOT an installer package"<<endl;

	return 0;
}